<?php

namespace app\home\controller;

use app\Controller;
use think\facade\Request;
use app\home\controller\Tool;
use app\home\controller\Player;

/**
 * 视频数据处理显示
 * Class Index
 * @package app\home\controller
 */
class Index extends Controller
{
    protected $wd;
    protected $api;
    protected $apiList;

    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        return $this->search();
    }

    /**
     * 初始化数据
     * @param $wd
     * @param $apiType
     */
    public function initialization($wd, $apiType)
    {
        $api = Tool::checkApi();
        if (!$api) return false;
        $this->wd = $wd;
        $this->apiList = $api; // api接口列表
        if ($apiType > count($api)) return false;
        $this->api = $api[$apiType];
        return true;
    }

    /**
     * 搜索内容
     * @param $wd
     * @return mixed|void
     */
    public function search($wd = '', $apiType = 0)
    {
        if (!$this->initialization($wd, $apiType)) {
            return "<script>alert('数据初始化失败');</script>";
        }
        $apiList = [];
        foreach ($this->apiList as $key => $item) {
            $apiList[$key] = explode('@', $item)[1];
        }
        $list = $this->toSearch($apiType);
        return $this->fetch('search', [
            'list' => $list,
            'title' => $wd == '' ? config('app_name') : $wd,
            'wd' => $wd,
            'domain' => Request::domain(),
            'apiList' => $apiList,
            'apiType' => $apiType,
        ]);
    }

    /**
     * 执行搜索api 选择
     * 将 api 搜索分配到单独控制器,便于后续维护
     */
    protected function toSearch($apiType)
    {
        $player = new Player($this->wd, $this->api);
        $controllerName = 'doSearch' . $apiType;
        return $player->$controllerName();
    }

}
